<template>
  <view class="content">
    <uv-toast ref="uToast"></uv-toast>
    <uv-no-network></uv-no-network>
    <Nav title="购物车"></Nav>
    <Header></Header>
    <view class="noCart" v-if="carList.length === 0">
      <uv-empty
          mode="car"
          text="购物车为空"
      ></uv-empty>
      <view class="btn" @click="aroundFn">
        <uv-button text="去逛逛" type="primary"></uv-button>
      </view>
    </view>
    <view class="hasCart" v-else>
      <view class="cartList"
            v-for="(item, index) in carList"
            :key="index"
      >

        <uv-checkbox-group  v-model="item.selected">
          <uv-checkbox
              :name="item.id"
              @change="(e) => onCheckboxChange(item, e)"
          />
        </uv-checkbox-group>

      <uv-image @click="jumpFn(item.goods_info)" :src="item.goods_info.goods_img" width="70px" height="70px"></uv-image>

      <view class="cartInfo">
        <view class="name" @click="jumpFn(item.goods_info)">{{ item.goods_info.goods_name }}</view>
        <view class="size" @click="jumpFn(item.goods_info)">36</view>
        <view class="box">
          <view class="price" @click="jumpFn(item.goods_info)">￥{{ item.goods_info.goods_price }}</view>
          <view class="btns">
            <uv-number-box :min="1"
                           v-model="item.number"
                           @change="(e) => onChange(item.id, e)"
            ></uv-number-box>
          </view>
        </view>
      </view>
    </view>

    <view class="bottom">
      <view class="cart">
        <view class="left">
          <uv-checkbox-group>
            <uv-checkbox @change="allSelect" />
          </uv-checkbox-group>
          <view class="all">全选</view>
        </view>
        <view class="right">
          <view class="total">合计: <text>￥{{totalPrice}}</text></view>
          <uv-button text="删除" type="error" @click="deleteFn"></uv-button>
          <uv-button text="结算" type="primary" @click="buyFn"></uv-button>
        </view>
      </view>
    </view>
  </view>
  </view>
</template>

<script setup>
import Header from "@/components/header.vue";
import Nav from "@/components/nav.vue";
import {onMounted, ref, computed} from "vue"
import {getCart, updateCart, deleteCart} from "@/request/api";

const pageNum = ref(1)
const carList = ref([])
const list = ref([])
const goods = ref([])
onMounted(() => {
  // 初始请求购物车数据
  refreshCart()
});
const refreshCart = () => {
  getCart({ pageNum: pageNum.value, pageSize: 10 })
      .then(res => {
        if (res.code === 0) {
          carList.value = res.result.list; // 更新购物车列表
          console.log('购物车列表:', carList.value);
          // 如果需要，基于总数再次请求数据
          if (res.result.total > 10) {
            return getCart({ pageNum: pageNum.value, pageSize: res.result.total });
          }
        }
      })
      .catch(error => {
        console.error("请求购物车数据失败:", error);
      });
};
const totalPrice = ref(0)
totalPrice.value = computed(() => {
  return goods.value.reduce((sum, item) => {
    return sum + (item.goods_price * item.number)
  }, 0)
})

// 全选功能
// const allSelect = (e) => {
//   carList.value.forEach(item => {
//     item.selected = e.value
//     onCheckboxChange(item, e.value)
//   })
// }
const onChange = (id, e) => {
  // 获取新的数量
  const newNumber = e.value; // 确保访问正确的值

  // 更新购物车
  updateCart(id, { number: newNumber, selected: true })
      .then(res => {
        if (res.code === 0) {
          // 更新成功，提示用户
          uni.showToast({
            title: '购物车更新成功',
            icon: 'success',
          });
        } else {
          // 处理更新购物车列表失败的情况，例如显示提示
          uni.showToast({
            icon: 'none',
            title: '更新购物车失败，请重试',
          });
          console.error('更新购物车失败:', res);
        }
      })
      .catch(error => {
        // 处理网络请求失败的情况
        uni.showToast({
          icon: 'none',
          title: '网络错误，请检查您的网络',
        });
        console.error('网络请求失败:', error);
      });
};
const onCheckboxChange = (item, e) => {
  if (e) {
    // 如果选中，则添加 ID 和对应的 goods_info 和 number
    if (!list.value.includes(item.id)) {
      list.value.push(item.id);
      goods.value.push({
        ...item.goods_info, // 展开原有的 goods_info
        number: item.number // 直接添加 item.number
      });
    }
  } else {
    // 如果取消选中，则移除 ID
    list.value = list.value.filter(itemId => itemId !== item.id);
    goods.value = goods.value.filter(goodsItem => goodsItem.id !== item.id); // 假设 goods_info 有 id
  }

  // console.log(item.number, '000');
  // console.log(goods.value, '当前商品列表'); // 输出当前商品列表
};
const allSelect = (e) => {
  if(e){

  }
}
const aroundFn = () => {
  uni.switchTab({
    url: "/pages/about/about"
  })
}
const deleteFn = () => {
  if (list.value.length === 0) {
    uni.showToast({
      icon: 'none',
      title: '请选择要删除的商品',
    });
    return; // 提前返回，避免后续代码执行
  }

  // 显示确认删除的模态框
  uni.showModal({
    title: '确定要删除吗？',
    content: '删除后不可恢复，确定要删除吗？',
    success: (res) => {
      if (res.confirm) {
        // 调用删除接口
        deleteCart({ ids: list.value })
            .then(res => {
              if (res.code === 0) {
                uni.showToast({
                  title: '删除成功',
                  icon: 'success',
                });
                // 清空选中的 ID 列表
                list.value = [];
                // 重新请求购物车数据
                refreshCart();
              } else {
                uni.showToast({
                  icon: 'none',
                  title: '删除失败，请重试',
                });
              }
            })
            .catch(error => {
              uni.showToast({
                icon: 'none',
                title: '网络错误，请检查您的网络',
              });
              console.error('删除失败:', error);
            });
      }
    },
  });
};
const jumpFn = (item) => {
  // console.log(item)
  uni.navigateTo({
    url: "/pages/detail/detail?id=" + item.id
  })
}
const buyFn = () => {
  if(goods.value.length === 0){
    uni.showToast({
      icon: 'none',
      title: '请选择要购买的商品',
    });
    return ;
  }
  uni.setStorageSync("GOODS", goods.value)
  console.log(goods.value, '000')
  uni.navigateTo({
    url: '/pages/buy/buy'
  });
}
</script>

<style lang="scss" scoped>
.content {
  height: calc(100vh - 88px);
  width: 100%;
  box-sizing: border-box;
  overflow-y: scroll;
  //border: 1px solid red;
  &::-webkit-scrollbar {
    display: none;
  }

  .noCart {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    height: 100%;
    .btn {
      margin-top: 20px;
    }
  }

  .hasCart {
    width: 100%;
    height: calc(100% - 70px); /* 减去头部和底部的高度 */
    box-sizing: border-box;
    //padding: 10px 20px;
    background-color: #f5f5f5;
    .cartList {
      width: 100%;
      padding: 15px;
      box-sizing: border-box;
      background-color: #FFFFFF;
      display: flex;
      margin-top: 10px;
      align-items: center;
      overflow: auto;
      .cartInfo {
        margin-left: 20px;
        width: calc(100% - 120px);
        box-sizing: border-box;

        .name {
          font-size: 18px;
          color: #333333;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
          width: 100%;
        }

        .size {
          font-size: 14px;
          color: #999999;
          margin-top: 5px;
        }

        .box {
          display: flex;
          justify-content: space-between;
          align-items: center;

          .price {
            font-size: 18px;
            color: red;
          }
        }
      }
    }

    .bottom {
      position: fixed;
      bottom: 0;
      width: 100%;
      left: 0;
      box-sizing: border-box;
      background-color: #FFFFFF;
      padding: 15px;
      z-index: 122;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
      .cart {
        display: flex;
        width: 100%;
        justify-content: space-between;
        align-items: center;

        .left {
          display: flex;
          align-items: center;
        }

        .right {
          display: flex;
          align-items: center;
          gap: 10px;
          .total {
            margin-right: 20px;
            text {
              color: red;
            }
          }
        }
      }
    }
  }
}
</style>